package com.netty.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netty.CIMUdpRequestHandler;
import com.netty.CIMWebSocketRequestHandler;
import com.netty.ImUdpServer;
import com.netty.config.properties.CIMProperties;
import com.netty.constant.Constants;
import com.netty.constant.SessionGroup;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;

/**
 * @author zl
 * @version 1.0
 * @date 2021/9/17 17:43
 */
@Slf4j
public class CIMUdpConfig implements CIMUdpRequestHandler {

    @Override
    public void channelActive(Channel channel) {

    }

    @Override
    public void channelRead0(Channel channel, DatagramPacket datagramPacket) {
        //获取发送内容
        String body = datagramPacket.content().toString(CharsetUtil.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(body);
        log.info(jsonObject.toString());
        //记录IP以及端口号
        InetSocketAddress sender = datagramPacket.sender();
        System.out.println("datagramPacket ======"+sender.getAddress().getHostAddress());
        System.out.println("datagramPacket ======"+sender.getPort());
        channel.attr(Constants.SessionConfig.UID).set(jsonObject.getString("uid"));
        channel.attr(Constants.SessionConfig.DEVICE_ID).set(jsonObject.getString("deviceId"));
        channel.attr(Constants.SessionConfig.IPS).set(sender.getAddress().getHostAddress());
        channel.attr(Constants.SessionConfig.PORT).set(sender.getPort());
        channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8)
                ,datagramPacket.sender()));
    }



}
